import React, { useEffect, useState } from 'react';
import { Card, Steps, Form, Button, Space, message, Row, Col } from 'antd';
import { useNavigate, useParams } from 'react-router-dom';
import { useDispatch, useSelector } from 'react-redux';
import type { RootState } from '../../store';
import type { AppDispatch } from '../../store';
import { fetchRuleDetail, createRule, updateRule, setCurrentRule } from '../../store/slices/ruleSlice';
import BasicInfoStep from '../../components/rule/BasicInfoStep';
import TableSelectStep from '../../components/rule/TableSelectStep';
import ConditionConfigStep from '../../components/rule/ConditionConfigStep';
import AggregateConfigStep from '../../components/rule/AggregateConfigStep';
import RulePreviewStep from '../../components/rule/RulePreviewStep';
import type { RuleConfig } from '../../types/rule';

const { Step } = Steps;

const steps = [
  {
    title: '基本信息',
    description: '设置规则名称和描述',
  },
  {
    title: '选择数据表',
    description: '选择要统计的数据表',
  },
  {
    title: '配置筛选条件',
    description: '设置数据筛选条件',
  },
  {
    title: '配置聚合函数',
    description: '设置统计聚合函数',
  },
  {
    title: '预览确认',
    description: '预览规则配置',
  },
];

const RuleConfigEdit: React.FC = () => {
  const navigate = useNavigate();
  const { id } = useParams<{ id: string }>();
  const dispatch = useDispatch<AppDispatch>();
  const { currentRule, loading } = useSelector((state: RootState) => state.rule);
  
  const [currentStep, setCurrentStep] = useState(0);
  const [form] = Form.useForm();

  useEffect(() => {
    if (id) {
      dispatch(fetchRuleDetail(id));
    } else {
      dispatch(setCurrentRule(null));
    }
  }, [dispatch, id]);

  useEffect(() => {
    if (currentRule) {
      form.setFieldsValue({
        basicInfo: currentRule.basicInfo,
        tables: currentRule.tables,
        joins: currentRule.joins,
        conditions: currentRule.conditions,
        groupBy: currentRule.groupBy,
        aggregates: currentRule.aggregates,
      });
    }
  }, [currentRule, form]);

  const handleNext = async () => {
    try {
      await form.validateFields();
      if (currentStep < steps.length - 1) {
        setCurrentStep(currentStep + 1);
      }
    } catch (error) {
      console.error('表单验证失败:', error);
    }
  };

  const handlePrev = () => {
    if (currentStep > 0) {
      setCurrentStep(currentStep - 1);
    }
  };

  const handleSave = async () => {
    try {
      const values = await form.validateFields();
      const ruleConfig: RuleConfig = {
        basicInfo: values.basicInfo,
        tables: values.tables || [],
        joins: values.joins || [],
        conditions: values.conditions || [],
        groupBy: values.groupBy || [],
        aggregates: values.aggregates || [],
      };

      if (id) {
        await dispatch(updateRule({ id, rule: ruleConfig })).unwrap();
        message.success('规则更新成功');
      } else {
        await dispatch(createRule(ruleConfig)).unwrap();
        message.success('规则创建成功');
      }
      navigate('/rule-config');
    } catch (error) {
      message.error('保存失败，请检查表单');
      console.error('保存失败:', error);
    }
  };

  const renderStepContent = () => {
    switch (currentStep) {
      case 0:
        return <BasicInfoStep form={form} />;
      case 1:
        return <TableSelectStep form={form} />;
      case 2:
        return <ConditionConfigStep form={form} />;
      case 3:
        return <AggregateConfigStep form={form} />;
      case 4:
        return <RulePreviewStep form={form} />;
      default:
        return null;
    }
  };

  return (
    <div>
      <Card>
        <Steps current={currentStep} style={{ marginBottom: 32 }}>
          {steps.map((item) => (
            <Step key={item.title} title={item.title} description={item.description} />
          ))}
        </Steps>
        
        <Form
          form={form}
          layout="vertical"
          initialValues={{
            basicInfo: {
              name: '',
              description: '',
              status: 'disabled',
            },
            tables: [],
            joins: [],
            conditions: [],
            groupBy: [],
            aggregates: [],
          }}
        >
          <div style={{ minHeight: 400 }}>
            {renderStepContent()}
          </div>
        </Form>

        <Row justify="center" style={{ marginTop: 32 }}>
          <Col>
            <Space>
              {currentStep > 0 && (
                <Button onClick={handlePrev}>
                  上一步
                </Button>
              )}
              {currentStep < steps.length - 1 && (
                <Button type="primary" onClick={handleNext}>
                  下一步
                </Button>
              )}
              {currentStep === steps.length - 1 && (
                <Space>
                  <Button onClick={() => navigate('/rule-config')}>
                    取消
                  </Button>
                  <Button type="primary" loading={loading} onClick={handleSave}>
                    保存
                  </Button>
                </Space>
              )}
            </Space>
          </Col>
        </Row>
      </Card>
    </div>
  );
};

export default RuleConfigEdit;